<?php

namespace app\index\controller;

use app\common\controller\Frontend;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        // 获取所有分类及其关联的项目
        $categoryModel = new \app\admin\model\Category;

        $categories = $categoryModel->with(['projects' => function($query) {
            $query->where('status', '1')->order('weigh DESC, id DESC');
        }])->where('pid', '1')->where('status', 'normal')
            ->order('weigh DESC, id DESC')
            ->select();

        // 处理数据格式
        $categoryData = [];
        foreach ($categories as $category) {
            $projects = [];

            // 处理项目数据
            if ($category->projects) {
                foreach ($category->projects as $project) {
                    $projects[] = [
                        'id' => $project->id,
                        'name' => $project->name,
                        'description' => $project->description,
                        'unit' => $project->unit,
                        'default_price' => $project->default_price,
                        'image' => $project->image ? cdnurl($project->image, true) : ''
                    ];
                }
            }

            $categoryData[] = [
                'id' => $category->id,
                'name' => $category->name,
                'image' => $category->image ? cdnurl($category->image, true) : '',
                'projects' => $projects
            ];
        }

        // 传递数据到视图
        $this->view->assign('categories', $categoryData);

        return $this->view->fetch();
    }

}
